//
//  AudioTool.m
//  wentong
//
//  Created by 谢英泽 on 16/4/11.
//  Copyright © 2016年 谢英泽. All rights reserved.
//

#import "AudioTool.h"
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>

static AVAudioPlayer *audioPlayer;
static SystemSoundID sound_id = 0;

@implementation AudioTool

+ (void)playAudioResource:(NSString *)name ofType:(NSString *)ext
{
    //通过配置文件来控制是否播放音效
//    if ([[NSUserDefaults standardUserDefaults] boolForKey:kUSER_closeSound]) return;
    
    if ([audioPlayer isPlaying]) return;
    NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:ext];
    if (path)
    {
        NSError *error;
        NSURL *music = [NSURL fileURLWithPath:path];
        //audioPlayer必须是全部变量，否则不会播放
        audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:music error:&error];
        
        BOOL isPlay;
        if (error){
            NSLog(@"%@",error);
        }else{
            //缓冲，提高播放的流畅度
            isPlay = [audioPlayer prepareToPlay];
            isPlay = isPlay ? [audioPlayer play] : NO;
        }
    }
}

+ (void)stopAudioPaly
{
    [audioPlayer stop];
}

+ (BOOL)isPlaying {
    return [audioPlayer isPlaying];
}

+ (void)playSystemSound:(NSString *)name ofType:(NSString *)ext
{
    //通过配置文件来控制是否播放音效
//    if ([[NSUserDefaults standardUserDefaults] boolForKey:kUSER_closeSound]) return;//关闭声音
    
    NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:ext];
    if (path) {
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)([NSURL fileURLWithPath:path]), &sound_id);
        AudioServicesPlaySystemSound(sound_id);
    }
}

@end
